/* 
 * 定义arcgis地图分析模块功能
 */
(function(window, angular, undefined){
	angular.module('arcgis.analysis', [])
	.factory('$arcgis_analysis', function($rootScope) {
		$arcgis_analysis = {
			/**
			 * arcgisdraw绘制的图形
			 */
			arcgisAnalysisObejct : {
				layerUrl:null,//分析图层（需要配置）
				classificationField:null,//分类字段或者统计类别字段
				classificationFieldAlias:null,//分类字段或者统计类别字段
				resultField:null,//分析结果字段和别名
				mapWkid:null,//地图服务的坐标系
				bufWkid:null,//缓冲区创建的坐标系统（必须为平面坐标系统）
				bufferDistances:null,//缓冲区距离
				gpsAnalysisType:null,//gps分析类型
				gpsAnalysisFile:null,//gps文件
				medname:null,//字典名称
				medroot:null,//字典名称
				mustmed:null,//字典名称
			},//参数type,geometry,Symbol,toolbar工具条
			
			analysisFeaturesResult:null,//分析结果元素
			//analysisGeometry:null,//分析图形,清理掉处理为rootScope里面的对象
			bufParams:null,
			queryOrgFeatures:null,
			projectParams:null,			
			analysisResult:{},//分析结果		
			analysisShowResult:{},//数据展示结果				
			mustBuffer:false,//是否需要构建缓冲区（目前存在geometry的图形在缓冲区距离为0时，容易出现错误）
			bufferGeomery:null,//buffer生成的图形的id
			
			//方法区域和参数区域-绘图方法区-start-
			
			getAlysisFeaturesResult:function(){
				return $arcgis_analysis.analysisFeaturesResult;
			},
			
			getArcgisAnalysisObejct:function(){
				return $arcgis_analysis.arcgisAnalysisObejct;
			},
			
			/** 
			 * 清除缓冲区绘制结果
			 */
			clearBufferGraphics : function(){
				if($arcgis_analysis.bufferGeomery!=null){
					//$rootScope.gisObject.map.graphics.remove($arcgis_analysis.bufferGeomery);
					delete $arcgis_analysis.bufferGeomery;
					$rootScope.clearGraphics();
					var geometry=$rootScope.analysisGeometry;
					if(geometry.type == "point"){
						$rootScope.addGraphic(geometry);
					}else if(geometry.type == "polyline"){
						var guid = $rootScope.getGUID();
						$rootScope.addLineGraphic(geometry,guid);
					}else{
						var guid = $rootScope.getGUID();
						$rootScope.addAnalysisDefaultGraphic(geometry,guid);
					}
					return;
				}			
			},

			/**
			 * 选中图形处理功能
			 * @param  {[type]} sn      [description]
			 * @param  {[type]} results [description]
			 * @return {[type]}         [description]
			 */
			selectGraphics:function(sn,results){
				$rootScope.deDrawAndClearGraphics();
				if(results==null || results.length<1){
					$.messager.alert("系统提示","图形为空，请重新选择");
					return;
				}else{
					
					var feature=results[0].feature;
					var geo=feature.geometry;

					if(geo.type == "point"){
						$rootScope.addGraphic(geo);
					}else if(geo.type == "polyline"){
						var guid = $rootScope.getGUID();
						$rootScope.addLineGraphic(geo,guid);
					}else{
						var guid = $rootScope.getGUID();
						$rootScope.addAnalysisDefaultGraphic(geo,guid);
					}
					$rootScope.analysisGeometry=geo;
				}
			},
			/**
			 * 选择图层信息
			 * @return {[type]} [description]
			 */
			analysisSelectGeomety:function(url,searchLayerIds,successf){
				$rootScope.deDrawAndClearGraphics();
				var distances = -1;
				$rootScope.drawPoint(function(geometry){
					$rootScope.deDrawAndClearGraphics();
					var sn={};
					sn.url=url;
					$rootScope.gisObject['analysisSelectGeomety']=sn;
					sn.searchLayerIds=searchLayerIds;
					$rootScope.innerIdentifySearch('analysisSelectGeomety', geometry,function(sn,results){
						$arcgis_analysis.selectGraphics(sn,results);
						if(successf){
							successf(results);
						}
					});
					
				});
			},

			/** 
			 * 开始绘制点
			 */
			analysisDrawPoint : function(){ 
				$rootScope.clearGraphics();
				$rootScope.analysisDrawType="point";
				$rootScope.drawPoint(function(geometry){
					$rootScope.analysisDrawType=null;
					$rootScope.deDraw();
					$rootScope.addGraphic(geometry);
					$rootScope.analysisGeometry=geometry;
					$arcgis_analysis.backspan();
				});
			},

			/**
			 * 开始绘制线
			 */
			analysisDrawPolyline : function(){ 
				$rootScope.clearGraphics();
				$rootScope.analysisDrawType="line";
				$rootScope.drawPolyline(function(geometry){
					$rootScope.analysisDrawType=null;
					$rootScope.deDraw();
					var guid = $rootScope.getGUID();
					$rootScope.addLineGraphic(geometry,guid);
					$rootScope.analysisGeometry=geometry;
					$arcgis_analysis.backspan();
				});
			},
			
			/** 
			 * 开始绘制面
			 */
			analysisDrawPolygon : function(){ 
				$rootScope.clearGraphics();
				$rootScope.analysisDrawType="polygon";
				$rootScope.drawPolygon(function(geometry){
					$rootScope.analysisDrawType=null;
					$rootScope.deDraw();
					var guid = $rootScope.getGUID();
					//$rootScope.addAnalysisDefaultGraphic(geometry,guid);
					$arcgis_analysis.addAnalysisDefaultGraphic(geometry,guid);
					$rootScope.analysisGeometry=geometry;
					$arcgis_analysis.backspan();
				});
			},
			
			/**
			 * 添加graphic
			 * geometry 线对象，guid 全局唯一值
			 */
			addAnalysisDefaultGraphic :function(geometry, guid){
				var gh = $rootScope.gisObject.map.graphics;
				if(!gh){
					return null;
				}
				guid = guid ? guid : $rootScope.getGUID();
		
				var outlineSyml = new esri.symbol.SimpleLineSymbol(
				esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([
						$rootScope.getDrawStyle().fillColor.r,
							$rootScope.getDrawStyle().fillColor.g,
							$rootScope.getDrawStyle().fillColor.b,
							$rootScope.getDrawStyle().fillOpacity]),
					$rootScope.getHighLightDefaultStyle().strokeWidth);
					
				var fillSymbol = new esri.symbol.SimpleFillSymbol(
					esri.symbol.SimpleFillSymbol.STYLE_SOLID,
					outlineSyml, new dojo.Color([
							254,
							0,
							0,
							0]));
				// 先添加绘制图形
				var graphic = new esri.Graphic(geometry, fillSymbol);
				if(!graphic.attributes){
					graphic.attributes = {};
				}
				graphic.attributes.$guid = guid;
				gh.add(graphic);
				return graphic;
			},

			/**
			 * 绘制结束函数
			 */
			backspan : function(){ 
				if(!$rootScope.isNullOrUndefined($rootScope.gisObject.map)){
					$rootScope.gisObject.map.setMapCursor("url("+getBasePath()+"/arcgis/images/cur/hand.cur),auto");
				}
			},
			
			//方法区域和参数区域 -绘图方法区--end-
			/**
			 * 叠加分析过程
			 * 01 获取geometry图形
			 * 02 坐标系统转换（转换成平面坐标系）
			 * 03 判断是否需要进行缓冲区分析，需要进入04缓冲区分析,不需要设置当前的geometry为分析的geometry,跳入05
			 * 04 缓冲区分析，创建分析的geometry
			 * 05 空间查询，查询所有关联的feature
			 * 06 将分析的的geometry分割成线
			 * 07 将空间查询的feature，分割成geometry
			 * 08 将分割成geometry与空间查询的feature构建对应关系成的新的graphic
			 * 09 将graphic投影成平面坐标
			 * 10 计算graphic的面积或者长度
			 * 11 计算分割之后的区域统计字段的新的值
			 * 12 数据展示
			 */
			analysis:function(){
				
				if($rootScope.analysisGeometry==null){
					console.log("01 获取geometry图形,geomety不存在！");
					return;
				}
				if(Math.abs($arcgis_analysis.arcgisAnalysisObejct.bufferDistances[0])<0.000000000000001){
					if($rootScope.analysisGeometry.type=='polygon'){
						$arcgis_analysis.mustBuffer=false;
					}else{
						$.messager.alert("非面图形，缓冲距离不能为空","系统提示");
						return;
					}
				}else{
					$arcgis_analysis.mustBuffer=true;
				}
				$arcgis_analysis.loadAnalysisParam();
				//装载的分析图形
				$arcgis_analysis.projectParams.geometries=[$rootScope.analysisGeometry];
				$arcgis_analysis.clearBufferGraphics();//清除缓存的图形问题
				$rootScope.bufferGeomery=null;//清理缓存图形问题
				$arcgis_analysis.bufferGeomery=null;//清理缓存图形问题
				$arcgis_analysis.geoserviceProjcet();
			},

			/**
			 * 装载分析参数
			 */
			loadAnalysisParam:function(){
				var go = $rootScope.gisObject;
				if(go.tywkid==null){
					$arcgis_analysis.arcgisAnalysisObejct.bufWkid=2382;
				}else{
					$arcgis_analysis.arcgisAnalysisObejct.bufWkid=go.tywkid.wkid;
				}
				
				if(go.mapisdlwkid){
					$arcgis_analysis.arcgisAnalysisObejct.mapWkid=go.dlwkid.wkid;
				}else{
					$arcgis_analysis.arcgisAnalysisObejct.mapWkid=go.tywkid.wkid;
				}
				
				
				/*if(go.dlwkid==null){
					$arcgis_analysis.arcgisAnalysisObejct.mapWkid=4610;
				}else{
					$arcgis_analysis.arcgisAnalysisObejct.mapWkid=go.dlwkid.wkid;
				}*/
				var projectParams= new esri.tasks.ProjectParameters();//映射参数
				var bufSR = new esri.SpatialReference({wkid : $arcgis_analysis.arcgisAnalysisObejct.bufWkid});//缓冲区的wkid
			    var outSR = new esri.SpatialReference({wkid : $arcgis_analysis.arcgisAnalysisObejct.mapWkid});//输出结果的wkid
			    projectParams.outSR = bufSR;
			    $arcgis_analysis.projectParams=projectParams;
			    $arcgis_analysis.bufParams = new esri.tasks.BufferParameters();
			    $arcgis_analysis.bufParams.unit = esri.tasks.GeometryService.UNIT_METER;
			    $arcgis_analysis.bufParams.bufferSpatialReference = bufSR;
			    $arcgis_analysis.bufParams.outSpatialReference = outSR;
			    $arcgis_analysis.bufParams.geodesic = true;
			
			},
			
			/**
			 * 读取gps文件信息
			 * @param  {[type]} gpsFileContext [description]
			 * @return {[type]}                [description]
			 */
			gpsReadgeomeryAndAnalysis:function(gpsFileContext){
				$arcgis_analysis.loadAnalysisParam();
		    	var type=1;
		    	 //gps格式验证
		        var geoString=$arcgis_analysis.checkGPSPoints(gpsFileContext,type);
		        var arcgisGemetrys;
		        try
		        {
		        	if(geoString!=null){
		        		if(geoString.charAt(0)=='_'){
		        			geoString=geoString.substring(1,geoString.length);
		        		}
		        	}
		        	var geometryType="polygon";
		            arcgisGemetrys = $arcgis_analysis.getArcgisGeometry(geoString,geometryType,$arcgis_analysis.arcgisAnalysisObejct.mapWkid);
		        }catch(e)
		        {
			       
			        $.messager.alert("系统提示","请检查文件中GPS点串格式！");
			        return;
		        }
		        //图形几何校正
		        $rootScope.gisObject.geometryService.simplify(arcgisGemetrys,function(simplifiedGeometries){
		        	  $rootScope.clearGraphics();
					  $rootScope.analysisGeometry =simplifiedGeometries[0];
					  var guid = $rootScope.getGUID();
					  $rootScope.addAnalysisDefaultGraphic($rootScope.analysisGeometry,guid);
		        	  
		        	  //图形分析功能
		        	  $arcgis_analysis.analysis();
		        },function(e){
		        	$.messager.alert("系统提示","不能分析,请检查文件中GPS点串格式！");
			        return;
		        });
			},
			
			/**
			 * gps分析功能
			 */
			gpsAnalysis:function(){
				if (window.FileReader) {
						var file = document.getElementById("fileField_dj").files[0];
						if(file==null){
							$.messager.alert("系统提示","请先导入gps文件");
							return;
						}
					    filename = file.name.split(".")[0];
					    var reader = new FileReader();
					    reader.onload = function() {
					    	//Forestar.App.AnalysisManager.instance.doAnalysis(this.result);
					    	console.log(this.result);
					    	var result=this.result;
					    	//文件代码在这个地方
					    	 $arcgis_analysis.gpsReadgeomeryAndAnalysis(result);
					    }
					    reader.readAsText(file); 
					} //支持IE 7 8 9 10
				else if (typeof window.ActiveXObject != 'undefined'){
					  //得不到正确的路径   处理了一下
					  var fil=document.getElementById("fileField_dj");
					  fil.select();
					  window.parent.document.body.focus();
					  var filePath = document.selection.createRange().text;
					  if(filePath == ""){
				        	$.messager.alert("系统提示","请选择GPS数据文件！");
				        	return;
				      }
					  var ForReading = 1;
					  var fso = new ActiveXObject("Scripting.FileSystemObject");
				      var textFile = fso.GetFile(filePath);
				      var ts = fso.OpenTextFile(filePath, ForReading); 
				      var result = ts.ReadAll();
				      console.log(result);
				      $arcgis_analysis.gpsReadgeomeryAndAnalysis(result);
				}else if (document.implementation && document.implementation.createDocument) { 
					    var xmlDoc; 
					    xmlDoc = document.implementation.createDocument("", "", null); 
					    xmlDoc.async = false; 
					    xmlDoc.load(document.getElementById("fileField_dj").value); 
					    console.log(xmlDoc.xml);
					    $arcgis_analysis.gpsReadgeomeryAndAnalysis(xmlDoc.xml);
				} else { 
					    $.messager.alert("系统提示","error");
					    return;
				}
			},
			
			
			/**
			* polygon点串转换为arcGis图形，支持多polygon,格式如下 图形与图形之间"_" 同一图形多环";" 点之间"," 同一点经纬度间"
			* "空格 sfr:空间参考
			*/
			getArcgisGeometry : function(pointStr, type, srf) {
				// 返回的图形数组
				var geoArr = new Array();
			    switch (type) {
					case "polygon" :
				      geoArr = $arcgis_analysis.getArcgisPolyGons(pointStr, srf);
				      break;
					case "polyline" :
					  geoArr = $arcgis_analysis.getArcgisPolyLines(pointStr, srf);
					  break;
					case "point" :
					  geoArr = $arcgis_analysis.getArcgisPoints(pointStr, srf);
					  break;
				}
				return geoArr;
			},
			  
			/**
			* polygon点串转换为arcGis图形，支持多polygon,格式如下 图形与图形之间"_" 同一图形多环";" 点之间"," 同一点经纬度间"
			* "空格 sfr:空间参考
			*/
			getArcgisPolyGons : function(pointStr, srf) {
			  	// 返回的图形数组
			  	var goeArr = new Array();
			  	var geoPointArr = pointStr.trim().split("_");
			  	var points = new Array();
			  	// 遍历不同图形
			  	for (var i = 0; i < geoPointArr.length; i++){
			  		var tGoe = new esri.geometry.Polygon(srf);
			  		var ringArr = geoPointArr[i].split(";");
			  		// 遍历同一图形不同的环
			  		for (var t = 0; t < ringArr.length; t++){
			  			var rings = new Array();
			  			// 拆分成一个个坐标点
			  			var strs = ringArr[t].split(",");
			  			var pArr = new Array();
			  			var p = null;

			  			for (var j = 0; j < strs.length; j++){
			  				var coors = strs[j].split(" ");
			  				if(coors.length!=2)
			  					throw new Error("数据格式不正确！");
			  				p = new esri.geometry.Point(Number(coors[0]),Number(coors[1]), srf);
			  				if(!isNaN(p.x)&&!isNaN(p.y)){
			  					rings.push(p);
			  				}else{
			  					throw new Error("数据格式不正确，请检查坐标！");
			  				}
			  			}
			  			tGoe.addRing(rings);
			  		}
			  		goeArr.push(tGoe);
			  	}
			  	return goeArr;
			},
		  	
		  	/**
		  	* polyLine点串转换为arcGis图形，支持多polyLine,格式如下 图形与图形之间"_" 点之间"," 同一点经纬度间" "空格
		  	* 
		  	* @param pointStr
		  	*            点串
		  	* @param sfr空间参考
		  	*/
		  	  getArcgisPolyLines : function(pointStr, srf) {
		  		// 返回的图形数组
		  		var goeArr = new Array();
		  		var geoPointArr = pointStr.substr(pointStr.indexOf(":")+1).split("_");
		  		// 遍历不同图形
		  		for (var i = 0; i < geoPointArr.length; i++) {
		  			var tGoe = new esri.geometry.Polyline(srf);
		  			var points = new Array();
		  			// 拆分成一个个坐标点
		  			var strs = geoPointArr[i].split(",");
		  			var p = null;
		  			for (var j = 0; j < strs.length; j++) {
		  				var coors = strs[j].split(" ");
		  				p = new esri.geometry.Point(Number(coors[0]), Number(coors[1]),
		  						srf);
		  				// 将点存放点数组
		  				points.push(p);
		  			}
		  			// rings.push(pArr);
		  			tGoe.addPath(points);
		  			goeArr.push(tGoe);
		  		}
		  		return goeArr;
		  	},
		
		  	/**
		  	 * point点串转换为arcGis图形， 支持多个point, 格式如下 图形与图形之间"_" 点之间"," 同一点经纬度间" "空格
		  	 * sfr:空间参考
		  	 */
		  	getArcgisPoints : function(pointStr, srf) {
		  		// 返回的图形数组
		  		var goeArr = new Array();
		  		var geoPointArr = pointStr.substr(pointStr.indexOf(":")+1).split("_");
		  		// 遍历不同图形
		  		for (var i = 0; i < geoPointArr.length; i++) {
		  			// 拆分成一个个坐标点
		  			var strs = geoPointArr[i].split(",");
		  			var p = null;
		  			for (var j = 0; j < strs.length; j++) {
		  				var coors = strs[j].split(" ");
		  				p = new esri.geometry.Point(Number(coors[0]), Number(coors[1]),
		  						srf);
		  				// 将点存放点数组
		  				goeArr.push(p);
		  			}
		  		}
		  		return goeArr;
		  	},
		  
		  	
		    /**
		    *
		    *检验坐标点是否符合规范
		    */
		    checkGeometryStr : function(str)
		    {	
				var strxArr = new Array();
				var stryArr = new Array();
				var geoPointArr = str.split("_");

				// 遍历不同图形
				for (var i = 0; i < geoPointArr.length; i++) {
					var strs = geoPointArr[i].split(",");

					for (var j = 0; j < strs.length; j++) {
						var coors = strs[j].split(" ");

						// 将x，y存放数组
						strxArr.push(coors[0]);
						stryArr.push(coors[1]);
					}
				}
				
		        if(strxArr.length!=stryArr.length)
		        	return false;
			
				return true;
		    },
		    //检查gps坐标格式
		    checkGPSPoints:function(result,type)
		    {
		    	//分组
		    	var GeoString="";
		    	var geoFenzu=1;
		    	var geoArray=result.split('\r\n');
		           var georesult="";
		           var tempList=null;
				    switch (type) 
				    {
				    	case 1 :
				    	if(geoArray.length>1)
				    	{    
				    		//判断第一行是否包含列名信息
				    		var t=geoArray[0].indexOf("编号");
				    		//不包含列名
				    		if(t<0)
				    		{ 
				    		  	//tab分隔
				    		  	if(geoArray[0].indexOf('\t')!=-1 
				    		  			&& geoArray[0].indexOf(' ')==-1 
				    		  			&& geoArray[0].indexOf(',')==-1){
									tempList=this.getBiaozhunString(geoArray,'\t',geoFenzu);
									georesult=tempList[0];
									geoFenzu=tempList[1];
				    		  	}
				    		  	//空格分隔
				    		  	if(geoArray[0].indexOf(' ')!=-1 
				    		  			&& geoArray[0].indexOf('\t')==-1 
				    		  			&& geoArray[0].indexOf(',')==-1){
									tempList=this.getBiaozhunString(geoArray,' ',geoFenzu);
									georesult=tempList[0];
									geoFenzu=tempList[1];
				    		  	 }
				    		  	 //逗号分隔
				    		  	 if(geoArray[0].indexOf(',')!=-1){
									tempList=this.getBiaozhunString(geoArray,',',geoFenzu);
									georesult=tempList[0];
									geoFenzu=tempList[1];
				    		  	 }
				    		 //包含列名
				    		 }else{
				    		  	 //tab分隔
				    		  	 if(geoArray[0].indexOf('\t')!=-1 
				    		  			 && geoArray[0].indexOf(' ')==-1){
									tempList=this.getBiaozhunString(geoArray,'\t',geoFenzu);
									georesult=tempList[0];
									geoFenzu=tempList[1];
				    		  	 }
				    		  	 //空格分隔
				    		  	 if(geoArray[0].indexOf(' ')!=-1 
				    		  			 && geoArray[0].indexOf('\t')==-1 ){
									tempList=this.getBiaozhunString(geoArray,' ',geoFenzu);
									georesult=tempList[0];
									geoFenzu=tempList[1];
				    		  	 }
				    		  	 //逗号分隔
				    		  	 if(geoArray[0].indexOf(',')!=-1 
				    		  			 && geoArray[0].indexOf('\t')==-1 
				    		  			 && geoArray[0].indexOf(' ')==-1 ){
									tempList=this.getBiaozhunString(geoArray,',',geoFenzu);
									georesult=tempList[0];
									geoFenzu=tempList[1];
				    		  	 }
				    		 }  
				    	}
				    	GeoString=georesult.substring(0,georesult.length-1);
				    	break;
				    }
				    return GeoString;
		        },
			    
			   /**
			    * 转换成符合条件的字符串
			    * @param geoArray
			    * @param splitStr
			    * @param geoFenzu
			    * @returns {Array}
			    */
			    getBiaozhunString:function(geoArray,splitStr,geoFenzu){
			    	var georesult="";
			    	for(i=0;i<geoArray.length;i++){
						var spgeo;
						spgeo=geoArray[i].split(splitStr);
						if(this.isValidate_row(spgeo)){
						   if(geoFenzu!=parseInt(spgeo[3]))
						    	{
						    	 geoFenzu=parseInt(spgeo[3]);
						    	 georesult=georesult.substring(0,georesult.length-1)+"_";
						    	}
					    	georesult+=spgeo[1]+" "+spgeo[2]+",";
						 }
					 }
			   		 return [georesult,geoFenzu];
			    },
			    
			    /**
			     * 判断一行内容是否有效
			     */
			    isValidate_row:function(xyList)
			    {
			     if(xyList && xyList.length>1 && 
			     	xyList[1] && xyList[2] && 
			     	parseFloat(xyList[1]) && 
			     	parseFloat(xyList[2]) && 
			     	parseFloat(xyList[3]))
			   		 return true;
			     else 
			     	return false;
			    },
			
			
			
				/**
				 * 投影转换
				 */
				geoserviceProjcet:function(){
					
					if($arcgis_analysis.mustBuffer){
						
						var go = $rootScope.gisObject;
						if(go.mapisdlwkid){
							//图形映射
							$rootScope.geoProject(
							$arcgis_analysis.projectParams.geometries,
							$arcgis_analysis.projectParams.outSR
								,function(geometries){
									console.log("投影转换成功，结果");
									console.log(geometries);
									$arcgis_analysis.bufParams.geometries = geometries;
									$arcgis_analysis.bufParams.distances=$arcgis_analysis.arcgisAnalysisObejct.bufferDistances;
									
									if($arcgis_analysis.mustBuffer){
										$arcgis_analysis.geoserviceBuffer();
									}else{
										//创建缓冲区图形
										//var graphic = new esri.Graphic(geometries[0], $rootScope.getDrawFillSymbol());
										var graphic = new esri.Graphic($arcgis_analysis.projectParams.geometries[0], $rootScope.getDrawFillSymbol());
										$arcgis_analysis.geoserviceQueryTask(graphic);
									}
		
								},function(e){
									console.log(e);
									$.messager.alert("系统提示","不能进行分析");
								}
							);
						}else{
							//处理逻辑为不需要进行投影转换的功能
							$arcgis_analysis.bufParams.geometries = $.extend(true, [], $arcgis_analysis.projectParams.geometries);
							$arcgis_analysis.bufParams.distances=$arcgis_analysis.arcgisAnalysisObejct.bufferDistances;
							
							if($arcgis_analysis.mustBuffer){
								$arcgis_analysis.geoserviceBuffer();
							}else{
								//创建缓冲区图形
								//var graphic = new esri.Graphic(geometries[0], $rootScope.getDrawFillSymbol());
								var graphic = new esri.Graphic($arcgis_analysis.projectParams.geometries[0], $rootScope.getDrawFillSymbol());
								$arcgis_analysis.geoserviceQueryTask(graphic);
							}
						}
						
					}else{
						//创建缓冲区图形
						//var graphic = new esri.Graphic(geometries[0], $rootScope.getDrawFillSymbol());
						var graphic = new esri.Graphic($arcgis_analysis.projectParams.geometries[0], $rootScope.getDrawFillSymbol());
						$arcgis_analysis.geoserviceQueryTask(graphic);
					}
				},
			/**
			 * 查询功能，空置时，执行函数
			 */
			geoserviceQueryTaskNullCallfunction:function(){
				console.log("空间查询结构为空");
				$.messager.alert("系统提示","查询结果为空！");
				return;
			},
			
			/**
			 * 查询功能出错误时，执行函数
			 */
			geoserviceQueryTaskErrorCallfunction:function(e){
				console.log("空间查询出错了,错误信息："+e);
				$.messager.alert("系统提示","不能进行分析，请重试！");
				return;
			},
			
			/**
			 * 投影转换失败时，执行函数
			 */
			geoserviceProjectErrorCallfunction:function(e){
				console.log("投影转换出错了,错误信息："+e);
				$.messager.alert("系统提示","不能进行分析，请重试！");
				return;
			},
			
			/**
			 * 构建空间关系失败时，执行函数
			 */
			geoserviceRelationErrorCallfunction:function(e){
				console.log("构建空间关系时出错了,错误信息："+e);
				$.messager.alert("系统提示","不能进行分析，请重试！");
				return;
			},
			
			/**
			 * 几何分割失败时，执行函数
			 */
			geoserviceCutErrorCallfunction:function(e){
				console.log("几何分割时出错了,错误信息："+e);
				$.messager.alert("系统提示","不能进行分析，请重试！");
				return;
			},
			
			/**
			 * 面积和长度计算失败时，执行函数
			 */
			geoserviceAreasAndLengthsErrorCallfunction:function(e){
				console.log("面积和长度计算出错了,错误信息："+e);
				$.messager.alert("系统提示","不能进行分析，请重试！");
				return;
			},

			numformate:function(value,l){
				if(!isNaN(value)){
					value=Number(value);
					value=value.toFixed(l);
					value=Number(value);
				}	
				return value;
			},
			
			
			/**
			 * geoservice查询功能
			 * @param graphic 缓冲区图形对象
			 * @param successFunction
			 * @param analysisTjlb 扩充统计函数
			 * @param errorFuntion
			 */
			geoserviceQueryTask:function(graphic,analysisTjlb){
				var MapServer=$arcgis_analysis.arcgisAnalysisObejct.layerUrl;
				//数据进行空间查询
				var QueryTask = new esri.tasks.QueryTask(MapServer);
				var query = new esri.tasks.Query();
				query.geometry = graphic.geometry; 
				query.wkid=$arcgis_analysis.arcgisAnalysisObejct.mapWkid;//wkid处理的
				query.outFields = ["*"]; 
				//TODO 暂时没有查明白为什么是4326后面清查
				//query.outSpatialReference = $rootScope.gisObject.map.spatialReference; 
				var go=$rootScope.gisObject;
				if(go.mapisdlwkid==true){
					query.outSpatialReference =go.dlwkid;
				}else{
					query.outSpatialReference = go.tywkid;
				}
				query.spatialRelationship = esri.tasks.Query.SPATIAL_REL_INTERSECTS;//相交关系
				query.returnGeometry = true;
				QueryTask.execute(query, function(result){
					console.log(" 05 空间查询结束，结果");
					console.log(result);
					
					var features=result.features;
					
					if(features==null || features.length<1){
						$arcgis_analysis.geoserviceQueryTaskNullCallfunction();
						return;
					}

					var attrs=[];

					for(var k=0;k<features.length;k++){
						attrs.push(features[k].attributes);
					}

					$rootScope.datadomainConvert(attrs,
						$arcgis_analysis.arcgisAnalysisObejct.medname,
						$arcgis_analysis.arcgisAnalysisObejct.medroot,
						$arcgis_analysis.arcgisAnalysisObejct.mustmed,function(data){
						if(data!=null){
							for(var k=0;k<features.length;k++){
								features[k].attributes=data[k];
							}
						}
						$arcgis_analysis.queryOrgFeatures=features;
						var fields=result.fields;
						//console.log("空间查询结果："+features);
						//空间查询小班的图形
						var geometryLst=[];
						for(var k=0;k<features.length;k++){
							geometryLst.push(features[k].geometry);
						}
						
						//将缓冲区图形分割成线
						var polyline=$arcgis_analysis.transPolygonToPolyline([graphic.geometry]);
						/**
						 * 将图形拆分
						 */
						$rootScope.gisObject.geometryService.cut(
							geometryLst,
							polyline,
							function(result){
								console.log("07 将空间查询的feature，分割成geometry,结果如下");
								console.log(result);
								//获取分割前的graphic集合，顺序以分割后的基础为准
								var cutedGraphicList=[];//分割之后的feature
								var cutedGeoList=[];//分割之后的查询小班信息
								cutedGeoList=cutedGeoList.concat(result.geometries); //分割之后的geometry
								
								//遍历分割的结果取得分割之前的 index-->graphic--->attribute
								for(var j=0;j<result.cutIndexes.length;j++)
								{
									var index=result.cutIndexes[j];
									cutedGraphicList.push(features[index]);//分割图形的小班属性信息
								}
								
								console.log(result.cutIndexes);
								
								var relationParams = new esri.tasks.RelationParameters();
								 relationParams.relation = esri.tasks.RelationParameters.SPATIAL_REL_IN;
								 relationParams.geometries1 = cutedGeoList;//分割后的geometry
								 //relationParams.geometries2 = res;
								 relationParams.geometries2 = [graphic.geometry];//空间查询出来的小班geometry(错误逻辑)，应该为查询区域的geomery（有缓存的话，是缓存之后的区域）
								 
								 //构建空间查询结果与分割之后的图形之间的关系
								 $rootScope.gisObject.geometryService.relation(relationParams,
								     function(relations){
									 	console.log("数据分析结果："+relations);
									 	
									 	//清空一下
										 var resultGraphicList = [];
										 // 将关系运算结束的几何图形存储起来
										 var resultGeoList = [];
										 
										 var useQueryTaskResultGeometry=[];
										 //取得关系运算前，各块的序号（geometry1Index），取得符合条件的分块小班。反推取得各块的，原小班属性信息。 将各小块挂上原小班属性信息，生成Graphic数组。
										 for (var j = 0; j < relations.length; j++) {
										 	 
											 var geoIndex = relations[j].geometry1Index;
											 console.log("对应关系："+geoIndex+"->"+relations[j].geometry2Index);
											 resultGeoList.push(cutedGeoList[geoIndex]);
											 
											 var attributeIndex= relations[j].geometry2Index;
											 var tempAttribute=cutedGraphicList[geoIndex].attributes;
											 var graphic = new esri.Graphic(cutedGeoList[geoIndex]);
											 
											 // var tempAttribute=features[attributeIndex].attributes;
											 // var graphic = new esri.Graphic(cutedGeoList[index]);
											 
											 graphic.attributes=jQuery.extend({},tempAttribute);
											 
											 useQueryTaskResultGeometry.push(cutedGraphicList[geoIndex].geometry);
											
											/* graphic.attributes.relationQueryFeatureIndex=geoIndex;*/
											 resultGraphicList.push(graphic); //重构的图形，包含分割前的图形属性信息和原来分割前的图形index
										 }
										 
										var geoProjectparams = new esri.tasks.ProjectParameters();
										//geoProjectparams.geometries = resultGeoList;
										
										var connectAllGeo=[];
										connectAllGeo=connectAllGeo.concat(resultGeoList);
										//connectAllGeo=connectAllGeo.concat(geometryLst);
										connectAllGeo=connectAllGeo.concat(useQueryTaskResultGeometry);
										
										geoProjectparams.geometries=connectAllGeo;
										geoProjectparams.outSR =new esri.SpatialReference({wkid : $arcgis_analysis.arcgisAnalysisObejct.bufWkid});//需要统一整理处理
										
										//投影转换成平台图形方便计算区域面积
										 $rootScope.geoProject(geoProjectparams.geometries,geoProjectparams.outSR,
											function(result){
											 
											 var c_geos=result;
											 var c_graphic=[];
											 for(var k=0;k<c_geos.length;k++){
												 var graphic = new esri.Graphic(c_geos[k]);
												 c_graphic.push(c_graphic);
											 }
											 //暂时可以不考虑统计区域的问题（坐标系统问题）直接面积计算
											 var areasAndLengthParams = new esri.tasks.AreasAndLengthsParameters();
											 areasAndLengthParams.areaUnit = esri.tasks.GeometryService.UNIT_SQUARE_KILOMETERS;
											 areasAndLengthParams.polygons = c_geos;//
											 //面积或者长度计算获取分割面积的百分比
											 $rootScope.geoAreasAndLengths(areasAndLengthParams.polygons,function(Arearesult){
												
												 console.log("面积计算：");
												 console.log(Arearesult);
												 console.log(Arearesult.areas);
												
												 for(var k=0;k<resultGraphicList.length;k++){
												 	var ArcgisComputerArea=Arearesult.areas[k];
												 	ArcgisComputerArea=$arcgis_analysis.numformate(ArcgisComputerArea,10);
													resultGraphicList[k].attributes.ArcgisComputerArea=ArcgisComputerArea;


													 var ArcgisQueryFeatureComputerArea=Arearesult.areas[resultGraphicList.length+k];
													 ArcgisQueryFeatureComputerArea=$arcgis_analysis.numformate(ArcgisQueryFeatureComputerArea,10);
													 resultGraphicList[k].attributes.ArcgisQueryFeatureComputerArea=ArcgisQueryFeatureComputerArea;
														
													
													var Valuepercentage=Arearesult.areas[k]/resultGraphicList[k].attributes.ArcgisQueryFeatureComputerArea;
													Valuepercentage=$arcgis_analysis.numformate(Valuepercentage,10);
													resultGraphicList[k].attributes.Valuepercentage=Valuepercentage;
													 
													 
													 console.log("面积计算："+resultGraphicList[k].attributes.ArcgisComputerArea+"/"
															 +resultGraphicList[k].attributes.ArcgisQueryFeatureComputerArea
															 +"="+ resultGraphicList[k].attributes.Valuepercentage);
													 
													 console.log("面积计算属性"+k);
													 console.log(resultGraphicList[k]);
												}
												$arcgis_analysis.analysisFeaturesResult=resultGraphicList;
												 
												 console.log("feature计算值：");
												 console.log(resultGraphicList);
												 if(analysisTjlb){
													analysisTjlb($arcgis_analysis.analysisFeaturesResult);
												 }else{
													$arcgis_analysis.analysisTjlb();
												 }
												 
											 },function(e){
													console.log(e);
													 $arcgis_analysis.geoserviceAreasAndLengthsErrorCallfunction(e);
											 });
										},function(e){
											console.log(e);
											 $arcgis_analysis.geoserviceProjectErrorCallfunction(e);
										});
								 	 },
								     function(e) {
								 		console.log(e);
								 		 $arcgis_analysis.geoserviceRelationErrorCallfunction(e);
									 });
								},
								function(e){
									console.log(e);
									$arcgis_analysis.geoserviceCutErrorCallfunction(e);
								});
						},function(e){

						});
				},
				function(e){
					console.log(e);
					$arcgis_analysis.geoserviceQueryTaskErrorCallfunction(e);
					//$.messager.alert("系统提示","不能进行分析");
				});
			},
			
			
			/**
			 * 显示缓冲区的图形
			 */
			ShowBufferGeometry:function(graphic){
				//有缓存处理图形问题
				$rootScope.clearGraphics();
				$arcgis_analysis.bufParams.outGeometries=[graphic.geometry];
				$arcgis_analysis.bufferGeomery=graphic.geometry;
				$rootScope.bufferGeomery=graphic.geometry;
				var guid = $rootScope.getGUID();
				//$rootScope.addAnalysisDefaultGraphic(graphic.geometry,guid);
				$arcgis_analysis.addBufferDefaultGraphic(graphic.geometry,guid);
				//设置地图视图范围
				var rExtent = $rootScope.getMaxExtent([graphic]);
		    	$rootScope.gisObject.map.setExtent(rExtent);
			},

			/**
			 * 添加graphic(红线边框，里面控制为空白的透明的效果)
			 * geometry 线对象，guid 全局唯一值
			 */
			addBufferDefaultGraphic :function(geometry, guid){
				var gh = $rootScope.gisObject.map.graphics;
				if(!gh){
					return null;
				}
				guid = guid ? guid : $rootScope.getGUID();

				var outlineSyml = new esri.symbol.SimpleLineSymbol(
				esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([
						$rootScope.getDrawStyle().fillColor.r,
							$rootScope.getDrawStyle().fillColor.g,
							$rootScope.getDrawStyle().fillColor.b,
							$rootScope.getDrawStyle().fillOpacity]),
					$rootScope.getHighLightDefaultStyle().strokeWidth);
					
				var fillSymbol = new esri.symbol.SimpleFillSymbol(
					esri.symbol.SimpleFillSymbol.STYLE_SOLID,
					outlineSyml, new dojo.Color([
							254,
							0,
							0,
							0]));
				// 先添加绘制图形
				var graphic = new esri.Graphic(geometry, fillSymbol);
				if(!graphic.attributes){
					graphic.attributes = {};
				}
				graphic.attributes.$guid = guid;
				gh.add(graphic);
				return graphic;
			},
			
			/**
			 * 创建缓冲去分析功能
			 */
			geoserviceBuffer:function(){
				//创建缓冲区
				$rootScope.gisObject.geometryService.buffer(
					$arcgis_analysis.bufParams,
					function(res){
						console.log("创建缓冲区成功，结果");
						console.log(res);
						//创建缓冲区图形
						var graphic = new esri.Graphic(res[0], $arcgis_analysis.getBufferSymbol());//缓冲区创建的symbol单独处理
						$arcgis_analysis.ShowBufferGeometry(graphic);
						$arcgis_analysis.geoserviceQueryTask(graphic);
					},function(e){
						console.log(e);
						$.messager.alert("系统提示","不能进行分析");
						return;
					}
				);
			},

			getBufferSymbol:function(){
				var outlineSyml = new esri.symbol.SimpleLineSymbol(
						 esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([
						   255, 0, 0, 0.9]), 2);
				var polygonSymbol =new esri.symbol.SimpleFillSymbol(
						 esri.symbol.SimpleFillSymbol.STYLE_SOLID,outlineSyml,
						 new dojo.Color([150, 0, 0, 0.4]));
				return polygonSymbol;
			},
			
			/**
			 * 统计信息梳理
			 */
			analysisTjlb:function(){
				if($arcgis_analysis.analysisFeaturesResult==null){
					$.messager.alert("系统提示","分析失败");
					return;
				}else{
					var result={};
					var resultLst=[];
					for(var k=0;k<$arcgis_analysis.analysisFeaturesResult.length;k++){
						var o_feature=$arcgis_analysis.analysisFeaturesResult[k];
						console.log("feature:"+k);
						console.log(o_feature);
						var value=o_feature.attributes[$arcgis_analysis.arcgisAnalysisObejct.classificationField];
						
						if(value==null || value=="undefined"){
							value="";
						}
						
						if(result[value]!=null){
							var tempValue=result[value];
							var itemValue=jQuery.extend(true,{},tempValue);
							for(var j=$arcgis_analysis.arcgisAnalysisObejct.resultField.length-1;j>-1;j--){
								
								var countValue=o_feature.attributes[$arcgis_analysis.arcgisAnalysisObejct.resultField[j].field]*
									o_feature.attributes['Valuepercentage'];
								
									console.log("数据展示统计值计算"+o_feature.attributes[$arcgis_analysis.arcgisAnalysisObejct.resultField[j].field]+"*"+o_feature.attributes['Valuepercentage']+"="+countValue);
									itemValue[$arcgis_analysis.arcgisAnalysisObejct.resultField[j].field]+=countValue;
							}
							result[value]=itemValue;
						}else{
							//result[value]=true;
							var itemValue={key:value};
							for(var j=$arcgis_analysis.arcgisAnalysisObejct.resultField.length-1;j>-1;j--){							
								var o_count_value=o_feature.attributes[$arcgis_analysis.arcgisAnalysisObejct.resultField[j].field];
								var Valuepercentage=o_feature.attributes['Valuepercentage'];
								
								
								var countValue=o_feature.attributes[$arcgis_analysis.arcgisAnalysisObejct.resultField[j].field]*
									o_feature.attributes['Valuepercentage'];
								
								console.log("数据展示统计值计算"+o_feature.attributes[$arcgis_analysis.arcgisAnalysisObejct.resultField[j].field]+"*"+o_feature.attributes['Valuepercentage']+"="+countValue);
								
								itemValue[$arcgis_analysis.arcgisAnalysisObejct.resultField[j].field]=countValue;
							}
							result[value]=itemValue;
							resultLst.push(value);
						}
					}
					console.log("数据展示:");
					console.log(result);
					$arcgis_analysis.analysisResult.keyLst=resultLst;//结果主键值
					$arcgis_analysis.analysisResult.keyResult=result;//查询结果信息
					$arcgis_analysis.analysisResult.queryXbLst=$arcgis_analysis.classificationStatistics();
					if($arcgis_analysis.showAnalysisResult!=null){
						$arcgis_analysis.showAnalysisResult($arcgis_analysis.analysisResult);
					}
				}
			},

			classificationStatistics:function(){
				if($arcgis_analysis.analysisFeaturesResult==null){
					//$.messager.alert("系统提示","分析失败");
					return null;
				}else{
					var result={};
					var resultLst=[];
					for(var k=0;k<$arcgis_analysis.analysisFeaturesResult.length;k++){
						var o_feature=$arcgis_analysis.analysisFeaturesResult[k];
						console.log("feature:"+k);
						console.log(o_feature);
						var objectKey=o_feature.attributes[$arcgis_analysis.arcgisAnalysisObejct.layerKey];
						
						if(objectKey==null || objectKey=="undefined"){
							objectKey="";
						}
						
						if(result[objectKey]!=null){
							var tempValue=result[objectKey];
							var itemValue=jQuery.extend(true,{},tempValue);
							var fields=["ArcgisComputerArea","Valuepercentage"];
							for(var j=fields.length-1;j>-1;j--){
								var i_field=fields[j];
								
								
								var countValue=o_feature.attributes[i_field];
								console.log(itemValue.attributes["MIAN_JI"]+"合计结果"+i_field+"："+countValue+"+"+itemValue.attributes[i_field]+"=");
								itemValue.attributes[i_field]+=countValue;
								console.log(itemValue.attributes[i_field]);
							}
							result[objectKey]=itemValue;
						}else{
							var itemValue=null;
							for(var h=0;h<$arcgis_analysis.queryOrgFeatures.length;h++){
								var org=$arcgis_analysis.queryOrgFeatures[h];

								var orgKey=org.attributes[$arcgis_analysis.arcgisAnalysisObejct.layerKey];
								if(orgKey==objectKey){
									itemValue=$.extend(true,null,org);
									var fields=["ArcgisComputerArea","Valuepercentage","ArcgisQueryFeatureComputerArea"];
									for(var j=fields.length-1;j>-1;j--){
										var i_field=fields[j];
										var value=o_feature.attributes[i_field];
										itemValue.attributes[i_field]=value;
									}

									
									break;
								}
							};
							
							result[objectKey]=itemValue;
							resultLst.push(objectKey);
						}
					}
					if(resultLst!=null && resultLst.length>0){
						var featurelst=[];
						for(var k=0;k<resultLst.length;k++) {
							feature=result[resultLst[k]];
							//$rootScope.addFeaturePopGraphic(feature,(k+1));
							featurelst.push(feature);
						}
						

						return featurelst;
					}
				}
			},
			
			/**
			将多个面图形，做成一个polyline的多线
			**/
			transPolygonToPolyline:function(polygonArr) {
			    var polyline = new esri.geometry.Polyline(polygonArr[0].spatialReference);
				for(var t=0;t<polygonArr.length;t++){
					var polygon=polygonArr[t];
			        for (var j = 0; j < polygon.rings.length; j++) {
			            for (var i = 0; i < polygon.rings[j].length - 1; i++) {
			               	polyline.addPath([
		                        new esri.geometry.Point(polygon.rings[j][i][0],
		                                polygon.rings[j][i][1]),
		                        new esri.geometry.Point(polygon.rings[j][i + 1][0],
		                                polygon.rings[j][i + 1][1])]);
			            }
			        }
		        }
			    return polyline;
			},
			
			/**
			 * 初始化分析参数
			 */
			initAnalysisParam:function(layerUrl,layerName,
				layerKey,classificationField,
				classificationFieldAlias,
				resultField,bufferDistances,
				medname,medroot,mustmed,
				showAnalysisFunction){
				$arcgis_analysis.arcgisAnalysisObejct.layerUrl=layerUrl;
				$arcgis_analysis.arcgisAnalysisObejct.layerName=layerName;
				$arcgis_analysis.arcgisAnalysisObejct.layerKey=layerKey;
				$arcgis_analysis.arcgisAnalysisObejct.classificationField=classificationField;//分类字段或者统计类别字段
				$arcgis_analysis.arcgisAnalysisObejct.classificationFieldAlias=classificationFieldAlias;//分类字段或者统计类别字段别名
				$arcgis_analysis.arcgisAnalysisObejct.resultField=resultField;//分类字段或者统计类别字段别名
				$arcgis_analysis.arcgisAnalysisObejct.bufferDistances=bufferDistances;

				$arcgis_analysis.arcgisAnalysisObejct.medname=medname;
				$arcgis_analysis.arcgisAnalysisObejct.medroot=medroot;
				$arcgis_analysis.arcgisAnalysisObejct.mustmed=mustmed;
				
				//初始化构造函数
				if(showAnalysisFunction!=null){
					$arcgis_analysis.showAnalysisResult=showAnalysisFunction;
				}
			},
		};

		for(f in $arcgis_analysis){
			$rootScope[f] = $arcgis_analysis[f];
		}
		return $arcgis_analysis;
	}).run(function($rootScope, $arcgis_analysis) { });
}(window, angular));